<template>
	<div class="container">
		<el-form>
			<div class="md-header">
				<el-form-item>
					<div class="article-title">
						<span class="title-label">文章标题</span>
						<el-input class="md-header-input" v-model="title" />
					</div>
					<div class="article-buttons">
						<!-- 保存草稿 -->
						<el-button class="draft-button" type="primary" @click="saveDraft()">保存草稿</el-button>
						<!-- 发布文章 -->
						<el-button class="publish-button" type="primary" @click="openDialog()">发布文章</el-button>
					</div>
				</el-form-item>
			</div>

			<el-form-item>
				<MdEditor class="mgb20" v-model="text" :toolbars="toolbars" />
			</el-form-item>

			<el-form-item>
				<!-- 保存草稿对话框出现 -->
				<div class="md-header-saveDraft">
					<!-- 保存草稿对话框 -->
					<el-dialog v-model="visible" 
							   title="发布文章" 
							   class="dialog blur-background" 
							   center 
							   :modal="true"
							   :close-on-click-modal="false" 
							   :close-on-press-escape="false" 
							   :modal-append-to-body="true"
							   :show-close="false">
							

						<!-- 第一行, 文章标签 -->
						<div class="label">
							<span class="span-text">文章标签</span>
							<el-tooltip placement="top">
								<template #content> 文章标签 <br />便于分类检索  <br /> 多个标签请用 '，' 分开</template>
								<span class="iconfont icon-wenhao-yuankuang"></span>
							</el-tooltip>
							<el-input v-model="labelValue" />
						</div>

						<!-- 第二行, 文章摘要 -->
						<div class="excerpt">
							<span class="span-text">文章摘要</span>
							<el-tooltip placement="top">
								<template #content> 文章摘要 <br />快速了解文章内容 </template>
								<span class="iconfont icon-wenhao-yuankuang"></span>
							</el-tooltip>
							<el-input v-model="textarea" 
									  maxlength="200" 
									  :autosize="{ minRows: 2, maxRows: 4 }"
									  type="textarea" 
									  placeholder="" 
									  class="text-input" />
						</div>

						<!-- 第三行, 文章封面 -->
						<div class="cover">
							<span class="span-text">文章封面</span>
							<el-tooltip placement="top">
								<template #content> 文章封面 <br /> 美化文章标题 </template>
								<span class="iconfont icon-wenhao-yuankuang"></span>
							</el-tooltip>

							<!-- 自动生成和上传一张图片 imageUrl -->
							<el-upload class="avatar-uploader" 
									   action="http://localhost:8081/api/upload"
									   :show-file-list="false" 
									   :on-success="handleAvatarSuccess"
									   :before-upload="beforeAvatarUpload">
								<img v-if="imageUrl" 
									 :src="imageUrl" 
									 class="avatar" 
									 :fit="fit" />
								<el-icon v-else class="icon iconfont icon-jiahao1">
									<Plus />
								</el-icon>
							</el-upload>

							<div class="third">
								<!-- 刷新 -->
								<div class="refresh" @click="refreshBtnClicked">
									<el-button>
										<span class="icon iconfont icon-shuaxin"></span>
									</el-button>
								</div>
							</div>
						</div>

						<!-- 文章分类 -->
						<div class="articleCate">
							<span class="span-text">文章分类</span>
							<el-tooltip placement="top">
								<template #content> 文章分类 <br />便于分类检索 </template>
								<span class="iconfont icon-wenhao-yuankuang"></span>
							</el-tooltip>
							<el-select v-model="articleCateValue" 
									   class="cateSelect" 
									   placeholder="Select">
									<el-option v-for="item in options" 
											   :key="item.value" 
											   :label="item.label"
											   :value="item.value" />
							</el-select>
						</div>
							<!-- 是否原创 -->
							<!-- <div class = "articleIsOriginal">
								<span class="span-text">是否原创</span>
								<el-tooltip placement="top">
									<template #content> 选择是否是原创文章 </template>
									<span class="iconfont icon-wenhao-yuankuang"></span>
								</el-tooltip>
								<div class="items">
	    							<el-radio-group v-model="radio" class="ml-4">
	      							<el-radio label="1">是</el-radio>
	      							<el-radio label="2">否</el-radio>
	    							</el-radio-group>
	  							</div>
							</div> -->

						<!-- 提交 取消 -->
						<div class="allbutton">
							<el-button type="primary" @click="publishArticle()">发布</el-button>
							<el-button type="primary" @click="visible = false">取消</el-button>
						</div>

					</el-dialog>
				</div>
			</el-form-item>

		</el-form>
	</div>
</template>
  
<script setup>
import { getCurrentInstance, ref } from 'vue';
import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import axios from 'axios';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';

const router = useRouter();

const title = ref('');
const text = ref('');
const visible = ref(false);
const imageUrl = ref('');
const stats = ref('');
const labelValue = ref('');
const textarea = ref('');
const articleCateValue = ref('');
const options = ref('');
const radio = ref();

const { proxy } = getCurrentInstance();

const textareaPattern = /^[\u4e00-\u9fa5\w]{0,200}.*[。]/;

// 上传文件的逻辑处理
const handleAvatarSuccess = function (response, uploadFile) {
	// imageUrl.value = URL.createObjectURL(uploadFile.raw)
	imageUrl.value = response.url;
}


// 限制图片类型, 并且图片大小不能超过2Mb
const beforeAvatarUpload = function (rawFile) {
	// if (rawFile.type !== 'image/jpeg' || rawFile.type !== 'image/jpg' || rawFile.type !== 'image.png') {
	// 	alert('只能上传jpeg, jpg, png类型的图片')
	// 	return false
	// } else 
	if (rawFile.size / 1024 / 1024 > 10) {
		alert('图片大小不能超过2MB!');
		return false;
	}

	return true
}

// 提交的表单
const formdatatosave = {
	title: '',
	content: '',
}

// 调出添加分类
function openDialogCar() {
	this.visible = false;
	this.innerVisible = true;
}

// 调出对话框
async function openDialog() {
	this.visible = true
	console.log(stats.value);

	// 自动获取文章摘要
	const textareaValue = this.text.match(textareaPattern);
	if (textareaValue && textarea.value != '') {
		textarea.value = textareaValue[0];
	}

	// 获取自动生成的图片
	if (title.value != '' && imageUrl.value == '') {
		const timeStamp = new Date().getTime();
		imageUrl.value = "http://localhost:8081/api/coverImg?text=" + title.value + `/?t=${timeStamp}`
	}
	else if (title.value == '' ) {
		imageUrl.value = '';
	}

	// 获取选择器中的文章分类选项
	try{
		const res = await axios.post('http://localhost:8081/api/getArticleCategory');
		if (res.data.code == 2000) {
			let data = res.data.data;
			const optionsArr = [];
			for (let key in data) {
				optionsArr.push({ value: key, label: data[key] });
			}
			options.value = optionsArr;
		}
	}catch(e){
		// 登录失败，提示用户
		console.log(e);
	}finally{
		//options = null;
	}
}

// 保存草稿的逻辑
async function saveDraft() {
	if(!title.value)
	{
		proxy.$message.error('请填写文章标题');
		return;
	}else if(!text.value)
	{
		proxy.$message.error('请输入文章内容');
		return;
	}

	const formDataArticle = {
		articleTitle: title.value,
		articleContentMd: text.value,
	}

	const url = 'http://localhost:8081/api/mdSave';

	try{
		const res = await axios.post(url, formDataArticle);
		if(res.data.code == 2000)
		{
			proxy.$message.success("保存成功");
		}
		else{
			proxy.$message.error(res.data.message);
		}

	}catch(e){
		proxy.$message.error(res.data.message);
	}

}

// 发布文章的逻辑
async function publishArticle() {
	if (!title.value || !text.value || !labelValue.value
	|| !textarea.value || !imageUrl.value || !articleCateValue.value) {
		proxy.$message.error('请将所有必填字段填写完整');
		return;
	}

	// 发送的数据
	const formDataArticle = {
		articleTitle: title.value,
		articleContentMd: text.value,
		articleTags: labelValue.value,
		articleTextArea: textarea.value,
		coverImageUrl: imageUrl.value,
		articleCate: articleCateValue.value,
	}

	const url = 'http://localhost:8081/api/insertArticle';

	try{
		const res = await axios.post(url, formDataArticle);
		if(res.data.code == 2000)
		{
			proxy.$message.success('发布成功');

			//跳转到home页中
			setTimeout(() => {
            	router.push("/pA");
          	}, 1000);
		}
		else{
			proxy.$message.error('发布失败');
		}
	}catch(e){
		proxy.$message.error('发布失败');
	}
}

// 刷新自动生成的文章图片
const refreshBtnClicked = () => {
	if (title.value != '') {
		imageUrl.value = "http://localhost:8081/api/coverImg?text=" + title.value;
		const timestamp = new Date().getTime();
		imageUrl.value += `/?t=${timestamp}`;
	}
	else if (title.value == '') {
		imageUrl.value = '';
	}
};

// 设置md编辑器工具栏
const toolbars = [
	'bold',
	'italic',
	'underline',
	'strikeThrough',
	'title',
	'sub',
	'sub',
	'quote',
	'unorderedList',
	'orderedList',
	'codeRow',
	'code',
	'link',
	'table',
	'mermaid',
	'katex',
	'-',
	'prettier',
	'htmlPreview',
	'catalog',
	'task',
	'=',
	'pageFullscreen',
	'fullscreen',
	'preview',
];

function handleSave() {
	console.log(title.value, text.value);
}

function handleCancel() {
	visible.value = false;
}

</script>
  
<style lang="scss">
.container {
	//filter: blur(6px);
	font-size: 14px;
	font-family: "Microsoft YaHei";
	line-height: 1.5;

	.md-header {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 14px 0;
		border-bottom: 1px solid #ebeef5;
		margin-bottom: 20px;

		.article-title {
			display: flex;
			align-items: center;
		}

		.title-label {
			margin: 10px;
			width: auto;
		}

		.md-header-input {
			height: 40px;
			border-radius: 6px;
			padding: 0 10px;
			width: 360px;
		}

		.article-buttons {
			display: flex;
			align-items: center;
		}

		.draft-button {
			margin-right: 10px;
			//background-color: #E6E6E6;
			//color: #333;
		}
	}

	.md-header-saveDraft {
		display: flex;
		align-items: center;

		.dialog {
			width: 50%;
			background-color: #fff;
			border-radius: 4px;
			box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
			align-items: center;

			.label {
				display: flex;
				align-items: center;
				margin-bottom: 16px;

				span:first-child {
					display: flex;
					align-items: center;
					margin-right: 12px;
				}

				.iconfont.icon-wenhao-yuankuang {
					border-radius: 10px;
					margin-right: 5px;
				}

				.el-input {
					width: auto;
				}
			}

			.excerpt {
				display: flex;
				align-items: center;
				margin-bottom: 10px;

				span:first-child {
					display: flex;
					align-items: center;
					margin-right: 12px;
				}

				.iconfont.icon-wenhao-yuankuang {
					border-radius: 10px;
					margin-right: 5px;
				}

				.text-input {
					flex: 1;
					border-radius: 5px;
				}
			}

.cover {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;

  .span-text {
    display: flex;
    align-items: center;
    margin-right: 12px;
  }

  .iconfont.icon-wenhao-yuankuang {
    border-radius: 10px;
    margin-right: 5px;
  }

  // 美化上传图片部分
  .avatar-uploader {
    width: 190px;

    & .el-icon {
      font-size: 28px;
      color: #8c939d;
      text-align: center;
      width: 200px;
      height: 150px;
      line-height: 150px;
    }

    & .avatar {
      width: 200px;
      height: 150px;
      display: block;
    }
  }

  // 隐藏上传文件列表和上传按钮
  el-upload {
    display: none;
  }

  .el-upload__list {
    display: none;
  }

  .third {
    margin: 20px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;

    // 刷新按钮部分
    .refresh {
      margin-bottom: 10px;

      & el-button {
        display: none;
      }
    }

    // 网络图片链接部分
    .urlimage {
      width: 100%;
      margin-top: 30px;

      & input {
        width: 100px;
      }
    }
  }
}


			.articleCate{
				display: flex;
				align-items: center;

				.span-text{
					display: flex;
					align-items: center;
					margin-right: 12px;					
				}

				.cateSelect{
					width: 200px;
				}
			}

			.articleIsOriginal{
				display: flex;
				align-items: center;
				margin-bottom: 16px;

				.span-text{
					display: flex;
					align-items: center;
					margin-right: 12px;		

					.items{
						width: auto;
					}
				}
			}

			.classification-wrapper {
  				display: flex;
  				align-items: center;
  
  				.span-text {
    				margin-right: 10px;
 				}
  
  				.el-input {
    				width: 150px;
    				margin-right: 10px;
    				.el-input__inner {
      					border: 1px solid #dcdfe6;
      					border-radius: 4px;
      					background-color: #f5f7fa;
      					color: #606266;
      					&:hover:not(.is-disabled):not(.el-input--suffix) .el-input__inner {
        					border-color: #c0c4cc;
      					}
    				}
  				}
  
  				.el-select {
    				flex: 1;
    				.el-input__inner {
    					border: 1px solid #dcdfe6;
      					border-radius: 4px;
      					background-color: #f5f7fa;
      					color: #606266;
      					&:hover:not(.is-disabled):not(.el-input--suffix) .el-input__inner {
        					border-color: #c0c4cc;
      					}
    				}
    			
					.el-select-dropdown__item.selected {
      					background-color: #f5f7fa;
    				}
    
					.el-select-dropdown__item:hover {
     					background-color: #ebeef5;
    				}
  				}
			}


			.allbutton {
				display: flex;
				justify-content: center;
				margin-top: 30px;

				button {
					width: 100px;
					margin: 0 10px;
				}

			}
		}
	}

}


.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.icon.iconfont.icon-jiahao1 {
	font-size: 28px;
	color: #8c939d;
	width: 100px;
	height: 100px;
	text-align: center;
}
</style>
  